using System;
using System.Net.Sockets;
using System.Text;
using System.Collections.Generic;

class User
{
    public static List<User> Instances = new List<User>();

    private Socket socket;
    private byte[] buffer;
    private PacketManager manager;

    const int BUFFER_SIZE = 1024;

    public User(Socket s)
    {
        socket = s;
        buffer = new byte[BUFFER_SIZE];
        manager = new PacketManager();

        Instances.Add(this);
    }

    public void Start()
    {
        try
        {
            socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, new AsyncCallback(onReceive), socket);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }

    private void onReceive(IAsyncResult ar)
    {
        Socket s = (Socket)ar.AsyncState;

        try
        {
            int count = s.EndReceive(ar);

            byte[] data = new byte[count];
            Array.Copy(buffer, 0, data, 0, count);

            manager.ReadData(data);

            if (count > 0)
            {
                s.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, new AsyncCallback(onReceive), s);
            }
        }
        catch (Exception ex)
        {
            Instances.Remove(this);
            Console.WriteLine(ex);//"Connection closed"
        }
    }

    private void print(byte[] bytes)
    {
        for (int i = 0; i < bytes.Length; i++)
        {
            Console.Write(" {0:X2}", bytes[i]);
        }
        Console.WriteLine();
    }
}
